<?php
namespace lib\db;
class Mysqlk
{
    private $oMysql;
    public static $instance=null;
    private function __construct($ip,$user,$pwd,$db,$port=3306,$charset='UTF8')
    {
        $this->oMysql=new \Mysqli($ip,$user,$pwd,$db,$port);
        if ($this->oMysql->connect_error)
        {
            $this->oMysql=false;
        }else
        {
            $this->oMysql->query("SET NAMES $charset");
        }
    }
    public static function Instance()
    {
        include WEBROOT.'/config/db.config.php';
        if(!self::$instance)
        {
            self::$instance=new  Mysqlk($db_host,$db_user,$db_pwd,$db_name);
        }
        return self::$instance;
    }
    public function lk()
    {
        return $this->oMysql;
    }
    public function __destruct()
    {
        if ($this->oMysql)$this->oMysql->close();
    }
    public function IsConnect()
    {
        return $this->oMysql?true:false;
    }
    public function select($sql,$cls_name=false)
    {
        if (!$this->IsConnect())return false;
        $q=$this->oMysql->query($sql);
        $arr=array();
        while($add=$q->fetch_assoc())
        {
            if ($cls_name) $arr[]=new DBRec($add);
            else $arr[]=$add;
        }
        $q->free();
        return $arr;
    }
    public function update($tbl,$arr,$c)
    {
        $arr1=array_keys($arr);
        $arr2=array_values($arr);
        $arr3=array();
        for ($i=0;$i<count($arr1);$i++){
            $arr3[$i]=$arr1[$i]."='".$arr2[$i]."',";
        }
        $aur1 =implode('',$arr3);
        $aur1=substr($aur1,0,strlen($aur1)-1);
        $sql="UPDATE $tbl SET $aur1 WHERE $c";
        //echo $sql;
        // exit;
        return $this->oMysql->query($sql);
    }
    public function insert($tbl,$arr_data)
    {
        $arr_field=array_keys($arr_data);
        $str_field="`".implode("`,`",$arr_field)."`";
        $str_value="'".implode("','",$arr_data)."'";
        $sql="INSERT INTO $tbl ($str_field) VALUES ($str_value)";
       // echo $sql;
        //exit;
        return $this->oMysql->query($sql);

    }
    public function delete($tbl,$sql)
    {
        $tbl="DELETE FROM $tbl";
        if ($sql) $sql=$tbl." WHERE ".$sql;
        return $this->oMysql->query($sql);
    }
    public function __call($name, $arguments)
    {
        if (!method_exists($this->oMysql,$name))
        {
            echo $name."不存在";
            exit;
        }
        return call_user_func_array(array($this->oMysql,$name),$arguments);
    }
}